<?php

namespace XWAM\Controller;

/**
 * 客户导入控制器
 *
 * @since 1.0 <2014-10-20> SoChishun <14507247@qq.com> Added.
 */
class CustomerImportController extends AppbaseController {

    // 导入客户数据表单 2014-12-30 by sutroon
    public function customer_import() {
        $this->display();
    }

    // 导入客户数据 2014-12-30 by sutroon
    public function customer_import_save() {
        $siteID = $this->user_login_data['siteID'];
        $userID = $this->user_login_data['id'];
        $skipDuplicate = I('skipDuplicate');
        $rule = I('rule');
        $msg = UploadHandlerAction::uploadToSite($siteID, 'CUSTOMER-IMPORT', array('subFolder' => 'CustomerExcel'), $userID, array('remark' => "$skipDuplicate,$rule"));
        if (!$msg['success']) {
            $this->act_error('导入失败：' . $msg);
        }
        $fid = $msg['data']['fileID'];
        if (!$fid) {
            $this->act_error('文件保存失败!');
        }
        $this->success('文件上传成功,即将处理数据...', U('Customer/customer_import_queue', 'i=0&fid=' . $fid));
    }

    // 导入客户数据队列检测 2014-12-31 by sutroon
    public function customer_import_queue() {
        $fid = I('fid');
        if (!$fid) {
            die('参数错误!');
        }
        $i = I('i', 0) + 1;
        $tp = create_taskqueue();
        if ($tp->add($id)) {
            $this->customer_import_save_data($fid);
            $tp->delete($id);
            $this->act_close_dialog(true, '导入成功!');
        } else {
            $this->success("系统繁忙,正在努力处理($i)...", U('Customer/customer_import_queue', 'i=' . $i . '&fid=' . $fid));
        }
    }

    // 导入客户数据 保存数据 2014-12-31 by sutroon
    function customer_import_save_data($fid) {
        if (!$fid) {
            die('文件编号不存在!');
        }
        $M = M('tgeneral_file');
        $data = $M->field('fileExt, filePath, remark, siteID, userID')->find($fid);
        if (!$data) {
            die('文件记录不存在');
        }
        if ($data['remark']) {
            $remarks = explode(',', $data['remark']);
            $skipDuplicate = $remarks[0] == '1' ? true : false; // 是否过滤重复数据
            $rule = count($remarks) > 1 ? $remarks[1] : 'order'; // 顺序保存或乱序保存
        }
        $siteID = $data['siteID'];
        $siteID = $data['userID'];
        $arrsql = array();
        $i = 0;
        $n = 0;
        $arrcontent = sofunc_excel_import(UPLOAD_ROOT . $data['filePath']);
        $dir = get_appdata_dir(array('siteID' => $this->user_login_data['siteID'], 'userID' => $this->user_login_data['id'], 'type' => 'tempsqls', 'subdir' => 'CustomerImp')) . date('Ymdhis');
        foreach ($arrcontent as $item) {
            if (trim($item) == '') {
                continue;
            }
            $arrsql[] = sprintf("('%s', '%s', '%s', 'IMPORT', %d, %d)", $item['客户姓名'], $item['电话号码'], $item['联系地址'], $userID, $siteID);
            if ($i > 0 && $i % 300 == 0) {
                $sql = 'insert into tcustomer_temp (personalName, telphone, address, exTags, userID, siteID) values ' . implode(',', $arrsql);
                $files[] = $dir . $n . '.sql';
                file_put_contents($dir . $n . '.sql', $sql);
                empty($arrsql);
                $n++;
            }
            $i++;
        }
        if ($arrsql) {
            $sql = 'insert into tcustomer_temp (personalName, telphone, address, exTags, userID, siteID) values ' . implode(',', $arrsql);
            $files[] = $dir . $n . '.sql';
            file_put_contents($dir . $n . '.sql', $sql);
            /**
              $result = $M->execute($sql);
              if (false === $result) {
              die($M->getDbError());
              } */
            $n++;
        }
        foreach ($files as $file) {
            $M->execute("load data infile '$file' into table tcustomer_temp");
        }
        sleep(5);
        $M->execute("insert into tcustomer (personalName, telphone, address, exTags, siteID) select personalName, telphone, address, exTags, siteID from tcustomer_temp where siteID=$siteID and userID=$userID");
        $M->execute("delete from tcustomer_temp where siteID=$siteID and userID=$userID");
        $this->act_close_dialog($result, '保存%!');
    }

}
